<template>
  <el-dialog :title="!dataForm.id ? '广告新增' : '广告修改'" :visible.sync="visible" :close-on-click-modal="false" append-to-body>
    <el-form :model="dataForm" ref="dataForm" :rules="dataRules" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="名称"/>
      </el-form-item>
      <el-form-item prop="coverUrl" label="图片">
        <avatar-uploader @uploaded="imageUploaded" :avatar="dataForm.coverUrl"/>
        <span style="font-size: 12px">小提示：建议上传大小为750*400(px)像素图</span>
      </el-form-item>
      <el-form-item label="位置" prop="positionId">
        <el-select v-model="dataForm.positionId" filterable placeholder="点击选择位置">
          <el-option
            v-for="item in cateList"
            :key="item.id"
            :label="item.positionBrief"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跳转链接">
        <el-select
          v-model="dataForm.moduleId"
          placeholder="点击选择链接"
          filterable
          clearable
          @change="moduleChange"
        >
          <el-option
            v-for="item in moduleList"
            :key="item.id"
            :label="item.moduleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <hr/>
      <el-form-item
        label="跳转详情"
        prop="params"
        v-if="visible && selectedModule && selectedModule.isParams"
      >
        <div v-if="count < 0">{{count}}</div>
        <el-input readonly v-model="dataForm.paramsName" disabled/>
        <news-category-selector
          @onSelect="selectParams"
          :selected-id="dataForm.params"
          v-if="selectedModule.modulePath === '/pages/news/news'"
        />
        <news-detail-selector
          @onSelect="selectParams"
          :selected-id="dataForm.params"
          v-if="selectedModule.modulePath === '/pages/news/news-detail'"
        />
        <course-detail-selector
          @onSelect="selectParams"
          :selected-id="dataForm.params"
          v-if="selectedModule.modulePath === '/pages/course/detail'"
        />

        <exam-cate-selector
          @onSelect="selectParams"
          :selected-id="dataForm.params"
          v-if="selectedModule.modulePath === '/pages/exam/exam-list'"
        />
        <daily-cate-selector
          @onSelect="selectParams"
          :selected-id="dataForm.params"
          v-if="selectedModule.modulePath === '/pages/exam/test-list'"
        />
        <exam-detail-selector
          @onSelect="selectParams"
          :selected-id="dataForm.params"
          v-if="selectedModule.modulePath === '/pages/exam/exam-detail'"
        />
<!--        <exam-detail-selector-->
<!--          @onSelect="selectParams"-->
<!--          :selected-id="dataForm.params"-->
<!--          v-if="selectedModule.modulePath === '/pages/exam/exam-detail'"-->
<!--        />-->
      </el-form-item>
      <el-form-item v-if="parseInt(dataForm.adType) === 2" label="链接" prop="val">
        <el-input type="text" v-model="dataForm.val" placeholder="URL"/>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button type="default" @click="onClone">取消</el-button>
      <el-button type="primary" @click="onSubmit" :loading="loading">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import AvatarUploader from '@/components/uploader/avatar-uploader'
  import NewsCategorySelector from '../sys/modular-selector/news-category-selector'
  import NewsDetailSelector from '../sys/modular-selector/news-detail-selector'
  import CourseDetailSelector from '../sys/modular-selector/course-detail-selector'
  import DailyCateSelector from '../sys/modular-selector/daily-cate-selector'
  import ExamCateSelector from '../sys/modular-selector/exam-cate-selector'
  import ExamDetailSelector from '../sys/modular-selector/exam-detail-selector'

  export default {
    name: 'notice-add',
    components: {
      AvatarUploader,
      NewsCategorySelector,
      NewsDetailSelector,
      CourseDetailSelector,
      DailyCateSelector,
      ExamCateSelector,
      ExamDetailSelector
    },
    data() {
      return {
        loading: false,
        count: 1,
        selectedModule: null,
        visible: false,
        moduleList: [],
        cateList: [],
        dataForm: {
          id: '',
          moduleId: '',
          positionId: '',
          name: '',
          coverUrl: '',
          adType: 1,
          params: '',
          paramsName: '',
          val: ''
          // sort: 0
        },
        dataRules: {
          positionId: [
            {required: true, message: '请选择位置', trigger: 'blur'}
          ],
          name: [{required: true, message: '请输入名称', trigger: 'blur'}],
          val: [{required: true, message: '请输入URL地址', trigger: 'blur'}],
          coverUrl: [{required: true, message: '请上传图片', trigger: 'blur'}],
          moduleId: [
            {required: true, message: '请输入URL地址', trigger: 'blur'}
          ],
          params: [{required: true, message: '请输入URL地址', trigger: 'blur'}]
        }
      }
    },
    methods: {
      selectParams(val) {
        this.$nextTick(() => {
          this.dataForm.params = val.id
          this.dataForm.paramsName = val.title
          // 刷新视图
          this.count++
        })
      },
      moduleChange(val) {
        this.selectedModule = this.moduleList.find(x => x.id === val)
      },
      async getCateList() {
        let res = await this.$http({
          url: this.$http.adornUrl(`/news-admin/adposition/select`),
          method: 'post'
        })
        this.cateList = res.data
      },
      async getmoduleList() {
        let res = await this.$http({
          url: this.$http.adornUrl(`/sys/module/select`),
          method: 'post'
        })
        this.moduleList = res.data
      },
      async init(id) {
        this.dataForm.id = id
        this.selectedModule = null
        this.visible = true
        this.$nextTick(async () => {
          this.$nextTick(() => this.$refs['dataForm'].resetFields())

          await this.getCateList()
          await this.getmoduleList()

          if (id) {
            let res = await this.$http({
              url: `/news-admin/adver/info/${id}`,
              method: 'post'
            })
            if (res.code === 200) {
              this.dataForm.id = res.data.id || ''
              this.dataForm.moduleId = res.data.moduleId
              this.dataForm.name = res.data.name
              this.dataForm.params = res.data.params
              this.dataForm.positionId = res.data.positionId
              this.dataForm.coverUrl = res.data.coverUrl
              this.dataForm.adType = res.data.adType
              this.dataForm.val = res.data.val
              let mid = this.dataForm.moduleId
              this.selectedModule = this.moduleList.find(x => x.id === mid)
            }
          }
        })
      },
      onSubmit() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            this.loading = true
            this.$http({
              url: this.$http.adornUrl(
                `/news-admin/adver/${!this.dataForm.id ? 'save' : 'update'}`
              ),
              method: 'post',
              data: {
                jumpType: 1,
                id: this.dataForm.id,
                coverUrl: this.dataForm.coverUrl,
                positionId: this.dataForm.positionId,
                name: this.dataForm.name,
                adType: this.dataForm.adType ? 1 : 0,
                val: this.dataForm.val,
                ossId: this.dataForm.adImage,
                params: (this.selectedModule && this.selectedModule.isParams === 1) ? this.dataForm.params : '',
                moduleId: this.dataForm.moduleId
                // 'sort': this.dataForm.sort
              }
            }).then(data => {
              if (data && data.code === 200) {
                this.$notify.success({
                  title: '提示',
                  message: '操作成功'
                })
                this.onClone()
                this.$emit('refreshDataList')
              } else {
                this.$notify.warning({
                  title: '提示',
                  message: data.msg
                })
              }
              this.loading = false
            })
          }
        })
      },
      onClone() {
        this.dataForm = {
          id: '',
          params: '',
          moduleId: '',
          positionId: '',
          name: '',
          coverUrl: '',
          adType: 1,
          val: ''
        }
        this.visible = false
      },
      imageUploaded(file) {
        this.dataForm.coverUrl = file.url
      }
    }
  }
</script>
<style lang="scss">
  .news-data-title {
    margin: 0;
    padding: 0;
    font-size: 13px;
    color: #333;
  }

  .news-data-page {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
</style>
                                                                                                                                                                                                                                                                                             
